/**
 * Created by Administrator on 2014/4/7.
 */
var LevelConsole = function (lineCanvas, mainLayer) {

    this.lineCanvas = lineCanvas;
    this.mainLayer = mainLayer;

    /**
     * 当前分数
     * @type {number}
     */
    this.currentScore = 0;
    /**
     * 当前等级
     * @type {number}
     */
    this.currentLevel = 1;
    /**
     * 提示数组
     * @type {Array}
     */
    this.hintArr = [];
    /**
     * 等级配置信息
     * @type {LevelConfig}
     */
    this.lvCfg = null;
    this.alignV = null;
    this.alignH = null;
    this.prizeTime = 0;
    this.prizeScore = 0;
    /**
     * 当前的地图信息
     * @type {Array}
     */
    this.mapArr = [];
    /**
     * 是否播放，用于暂停开关的
     * @type {boolean}
     */
    this.isPlaying = true;
    /**
     * 最核心的计算类
     * @type {Calculator}
     */
    this.calculator = new Calculator();
    /**
     * 当前选择的tile
     * @type {TileMc}
     */
    this.selectedTile = null;
    /**
     * 所有的tile使用键值对存储
     * @type {Object}
     */
    this.allTileMap = null;


}

LevelConsole.prototype.score = function (arg) {
    if (arguments.length == 1) {
        this.currentScore = arg;
    } else {
        return this.currentScore;
    }
}
LevelConsole.prototype.pause = function (flag) {
    if (arguments.length == 1) {
        this.isPlaying = !flag;
        if (flag) {
            //暂停
        } else {
            //恢复暂停
        }
    } else {
        return !this.isPlaying;
    }
}


LevelConsole.prototype.reset = function (lv) {
    var lvCfg = null;
    var tempArr = null;
    this.score(0);
    lvCfg = Data["level" + lv];
    this.lvCfg = lvCfg;
    if (lvCfg == null) {
        trace("stage all pass");
        return;
    }
    this.hintArr = [];
    Data.currentLevel = lv;
//    myTimer.reset(lvCfg.time);
    this.currentLevel = lv;
    this.alignV = lvCfg.vAlign;
    this.alignH = lvCfg.hAlign;
    this.prizeTime = lvCfg.prizeTime;
    this.prizeScore = lvCfg.prizeScore;
    this.pause(false);
    //初始化数据
    this.mapArr = new Array(Data.row);
    var row = 0;
    var line = 0;
    while (row < this.mapArr.length) {
        this.mapArr[row] = new Array(Data.line);
        line = 0;
        while (line < this.mapArr[row].length) {
            this.mapArr[row][line] = 0;
            line++;
        }
        row++;
    }
    this.calculator = new Calculator();
    var fillArr = this.calculator.getAllPicArr(this.calculator.getPicTypeArr(lvCfg.picNumbers));
    if (lvCfg.minPairs != null) {
        this.calculator.setConnectPicArr(this.mapArr, fillArr, lvCfg.minPairs);
    }
    //添加边界
    tempArr = [];
    row = 0;
    while (row < Data.line) {
        tempArr.push(-1);
        row++;
    }
    this.mapArr.unshift(tempArr);
    this.mapArr.push(tempArr.concat());
    row = 0;
    while (row < this.mapArr.length) {
        this.mapArr[row].unshift(-1);
        this.mapArr[row].push(-1);
        row++;
    }
    this.drawMapTile(this.mapArr, fillArr);

    this.checkResetPicIndex();

    //监听事件
    cc.NotificationCenter.getInstance().addObserver(this, this.tileClickHandler, EVENT_ITEM_CLICK, null);
}

/**
 *随机排列
 * @param mapArr
 * @param fillArr 需要用这个数组来填充mapArr
 *
 */
LevelConsole.prototype.drawMapTile = function (mapArr, fillArr) {
    var tile = null;
    var randomIndex = 0;
    this.selectedTile = null;
    this.mainLayer.removeAllChildren();
    this.allTileMap = new Object();
    for (var row in mapArr) {
        for (var line in mapArr[row]) {
            if (mapArr[row][line] == 0) {
                if (fillArr.length == 0) {
                    continue;
                }
                randomIndex = int(fillArr.length * Math.random());
                mapArr[row][line] = fillArr[randomIndex];
                fillArr.splice(randomIndex, 1);
            } else if (mapArr[row][line] == -1) {
                mapArr[row][line] = 0;
                continue;
            }

            tile = TileMc.create(mapArr[row][line]);
            tile.point(int(row), int(line));
            tile.setPosition(cc.p(int(line) * Data.tileWidth, int(row) * Data.tileHeight));
            this.mainLayer.addChild(tile);
            this.allTileMap[row + "_" + line] = tile;
        }
    }
}
/**
 * 绘制连通的线条
 * @param path
 */
LevelConsole.prototype.drawLine = function (path) {
    var canvas = this.lineCanvas;
    canvas.clear();
    var index = 0;
    canvas.alpha = 0.1;
    for (var i = 0; i < path.length - 1; i++) {
        canvas.drawSegment(cc.p(path[i][1] * Data.tileWidth, path[i][0] * Data.tileHeight),
            cc.p(path[i + 1][1] * Data.tileWidth, path[i + 1][0] * Data.tileHeight), 1, cc.c4f(1, 1, 1, 1));
    }
    canvas.runAction(cc.Sequence.create(cc.FadeIn.create(0.1), cc.FadeOut.create(0.2)));
    setTimeout(function () {
        this.lineCanvas.clear();
    }, 300, this);
}
/**
 * 检查是否还有路可走
 * @param flag
 */
LevelConsole.prototype.checkResetPicIndex = function (flag) {
    if (arguments.length == 0) {
        flag = false;
    }
    var pos = null;
    var tile = null;
    var now = new Date().getTime();
    var path = this.calculator.getHintResult(this.mapArr);
    trace("getHintResult use time:" + (new Date().getTime() - now) + " ms");
    if (path == null) //找不到提示路径，直接重新打乱图片位置
    {
        this.resetPicArr();
        return;
    }
    if (path.length == 0) //图片都被点击完了
    {
        this.levelClear();
        return;
    }
    if (!flag) {
        return;
    }
    pos = path[0];
    tile = this.allTileMap[pos[0] + "_" + pos[1]];
    if (this.hintArr.indexOf(tile) == -1) {
        this.hintArr.push(tile);
    }
    pos = path[path.length - 1];
    tile = this.allTileMap[pos[0] + "_" + pos[1]];
    if (this.hintArr.indexOf(tile) == -1) {
        this.hintArr.push(tile);
    }
}

LevelConsole.prototype.levelClear = function (param1) {
    trace("stage complete!");
    this.pause(true);
//    this.dispatchEvent(new MyEvent(Game.LEVEL_OVER,
//        {
//            "time":myTimer.count,
//            "score":currentScore
//        }));
}

LevelConsole.prototype.resetPicArr = function () {
    var resultArr = null;
    cc.NotificationCenter.getInstance().addObserver(this, this.tileClickHandler, EVENT_RESORTING, null);
    cc.NotificationCenter.getInstance().addObserver(this, this.tileClickHandler, EVENT_TIME_PAUSE, null);
    //延迟是因为要显示文字
    setTimeout(function () {
        while (resultArr == null) {
            trace("resetPic sort...............");
            this.calculator.resetPic(this.mapArr);
            resultArr = this.calculator.getHintResult(this.mapArr);
        }

        //blink
        for (var key in this.allTileMap) {
            var tile = this.allTileMap[key];
            tile.runAction(cc.Blink.create(1, randomInt(5, 10)));
        }
        //白光
        setTimeout(function () {
            cc.NotificationCenter.getInstance().addObserver(this, this.tileClickHandler, EVENT_RESOR_COMPLETE, null);
            var size = cc.Director.getInstance().getWinSize();
            var colorLayer = cc.LayerColor.create(cc.c4b(255, 255, 255, 255), size.width, size.height);
            this.mainLayer.getParent().addChild(colorLayer, 10000);
            colorLayer.runAction(cc.Sequence.create(cc.FadeIn.create(0.25), cc.FadeOut.create(0.25), cc.CallFunc.create(this.removeFromParentAndCleanup)));
        }, 1000, this);
        //重排
        setTimeout(function () {
            this.drawMapTile(this.mapArr, []);
        }, 1250, this);
        setTimeout(function () {
            cc.NotificationCenter.getInstance().addObserver(this, this.tileClickHandler, EVENT_TIME_RESUME, null);
        }, 1500, this);
    }, 1000, this);
}

/**
 * 点击一个元素后的处理方法
 * @param tile
 */
LevelConsole.prototype.tileClickHandler = function (tile) {
    var path = null;
    if (this.selectedTile == null) {
        this.selectedTile = tile;
        this.selectedTile.select(true);
    }
    else {
        if (this.selectedTile == tile) {//点击相同的点，直接返回
            return;
        }
        if (this.selectedTile.index() != tile.index()) { //不通图案，交换选择
            this.selectedTile.select(false);
            this.selectedTile = tile;
            this.selectedTile.select(true);
        }
        else {
            path = this.calculator.isConnected(this.mapArr, this.selectedTile.point(), tile.point());
            if (path != null) {
                if (this.hintArr.indexOf(this.selectedTile) == -1 || this.hintArr.indexOf(tile) == -1) {
                    this.currentScore = this.currentScore + this.prizeScore;
                }
                else {
                    this.hintArr.splice(this.hintArr.indexOf(this.selectedTile), 1);
                    this.hintArr.splice(this.hintArr.indexOf(tile), 1);
                }
                tile.dispose();
                this.selectedTile.dispose();
                this.mapArr[tile.point().r][tile.point().l] = 0;
                this.mapArr[this.selectedTile.point().r][this.selectedTile.point().l] = 0;
                this.selectedTile = null;
                this.drawLine(path);
                SoundManager.playEffect(SoundManager.PATH_CLEAR_TILE);
                setTimeout(this.checkResetPicIndex, 250, this);
//                setTimeout(checkRetract, 100, path[0][0], path[0][1], path[path.length - 1][0], path[path.length - 1][1]);
                return;
            }
            //不相通，则交换选择
            this.selectedTile.select(false);
            this.selectedTile = tile;
            this.selectedTile.select(true);
        }
    }
}
